//
//  ZDPhotoBrowserCell.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/11/9.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDPhotoBrowserCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImage+ZDScaleImage.h"


@interface ZDPhotoBrowserCell () <UIScrollViewDelegate>

@property (nonatomic, strong) NSURL *url;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIActivityIndicatorView *activityView;

@end

@implementation ZDPhotoBrowserCell


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self prepareUI];
    }
    
    return self;
}


///准备UI
- (void)prepareUI
{
    //添加子控件
    [self.contentView addSubview:self.scrollView];
    [self.scrollView addSubview:self.imageView];
    [self.contentView addSubview:self.activityView];
    
    
    //添加约束
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.activityView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[sv]-0-|" options:0 metrics:nil views:@{@"sv": self.scrollView}]];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[sv]-0-|" options:0 metrics:nil views:@{@"sv": self.scrollView}]];
    
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_activityView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_activityView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    
    
    //设置缩放系数
    self.scrollView.maximumZoomScale = 2.0;
    self.scrollView.minimumZoomScale = 0.5;
}

- (void)setModel:(ZDPhotoBrowserModel *)model
{
    _model = model;
    
    self.url = model.url;
}

- (void)setUrl:(NSURL *)url
{
    _url = url;
    
    if (!url)
    {
        return;
    }
    
    //每次进来都清空imageView 避免cell重用带来的影响
    self.imageView.image = nil;
    
    //清除cell子控件的相关属性 避免cell重用带来的影响
    [self clearCellAttributes];
    
    [self.activityView startAnimating];
    
    [self.imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        [self.activityView stopAnimating];
        
        if (error)
        {
            ZDLog(@"下载大图失败:%@", error);
            
            return;
        }
        
        [self layoutImageViewWithImage:image];
    }];
}


//清除cell子控件的相关属性 避免cell重用带来的影响
- (void)clearCellAttributes
{
    self.imageView.transform = CGAffineTransformIdentity;
    
    self.scrollView.contentInset = UIEdgeInsetsZero;
    self.scrollView.contentOffset = CGPointZero;
    self.scrollView.contentSize = CGSizeZero;
}


///根据图片的size来确定imageView的frame
- (void)layoutImageViewWithImage:(UIImage *)image
{
    CGSize newSize = [image disPlaySize];
    
    if (newSize.height < ZDScreenSize.height)
    {
        CGFloat offsetY = (ZDScreenSize.height - newSize.height) * 0.5;
        
//        self.imageView.frame = CGRectMake(0, offsetY, newSize.width, newSize.height);
        self.imageView.frame = CGRectMake(0, 0, newSize.width, newSize.height);
        
        //如果设置frame，在放大图片时
        self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, 0, offsetY, 0);
    }
    else
    {
        self.imageView.frame = CGRectMake(0, 0, newSize.width, newSize.height);
        
        self.scrollView.contentSize = newSize;
    }
    
}


/////等比缩放图片
//- (CGSize)disPlaySizeWithImage:(UIImage *)image
//{
//    CGFloat newWidth = ZDScreenSize.width;
//    
//    CGFloat newHeight = newWidth * (image.size.height / image.size.width);
//    
//    return CGSizeMake(newWidth, newHeight);
//}


#pragma mark - scrollView代理方法
//缩放哪个view
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}

//该方法在缩放时调用  会执行多次  缩放改变的是view的frame  view的bounds并没有改变
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    ZDLog(@"transform:%@", NSStringFromCGAffineTransform(self.imageView.transform));
    
    if (self.imageView.transform.a < 1.0)
    {
        if ([self.delegate respondsToSelector:@selector(viewForTransparent)])
        {
            [self.delegate viewForTransparent].alpha = self.imageView.transform.a;
        }
    }
}

//结束缩放时调用
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    //获取imageView的frame
    CGRect endFrame = self.imageView.frame;
    
    CGFloat offsetX = (ZDScreenSize.width - endFrame.size.width) * 0.5;
    CGFloat offsetY = (ZDScreenSize.height - endFrame.size.height) * 0.5;
    
    //offsetX 或者 offsetY小于0时，说明此时imageView比屏幕宽，或者高。如果直接使用offsetX和offsetY设置contentInset(最终内容与scrollView的间距)的话，那么最终放大后的图片就无法滚动了。所以这里将offsetX和OoffsetY重置为0
    if (offsetX < 0)
    {
        offsetX = 0;
    }
    
    if (offsetY < 0)
    {
        offsetY = 0;
    }
    
    
    if (self.imageView.transform.a < 0.7)
    {
        //取出对应的缩略图
        UIImageView *thumbImageView = self.model.imageView;
        
        //坐标系转换
        CGRect rect = [thumbImageView.superview convertRect:thumbImageView.frame toCoordinateSpace:self];
        
//        ZDLog(@"%@", NSStringFromCGRect(rect));
        
        [UIView animateWithDuration:0.25 animations:^{
            
            //不能设置bounds
            self.imageView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
            
            self.scrollView.contentInset = UIEdgeInsetsMake(rect.origin.y, rect.origin.x, 0, 0);
            
            self.scrollView.contentOffset = CGPointMake(-rect.origin.x, -rect.origin.y);
            
        } completion:^(BOOL finished) {
            
            if ([self.delegate respondsToSelector:@selector(dismiss)])
            {
                [self.delegate dismiss];
            }
        }];
    }
    else
    {
        [UIView animateWithDuration:0.25 animations:^{
            //设置结束缩放后 图片居中显示
            self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, offsetY, offsetX);
        }];
    }
}


#pragma mark 懒加载
- (UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        _scrollView = [[UIScrollView alloc] init];
        
        _scrollView.delegate = self;
    }
    
    return _scrollView;
}

- (ZDImageView *)imageView
{
    if (!_imageView)
    {
        _imageView = [[ZDImageView alloc] init];
    }
    
    return _imageView;
}

- (UIActivityIndicatorView *)activityView
{
    if (!_activityView)
    {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        
//        _activityView.color = [UIColor lightGrayColor];
    }
    
    return _activityView;
}

@end
